/**
 * Copyright (c) 2012 Georg Ehrke <ownclouddev at georgswebsite dot de>
 * Copyright (c) 2011 Bart Visscher <bartv@thisnet.nl>
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 * See the COPYING-README file.
 */

Calendar={
   Util:{
      dateTimeToTimestamp:function(dateString, timeString){
         dateTuple = dateString.split('-');
         timeTuple = timeString.split(':');
         
         var day, month, year, minute, hour;
         day = parseInt(dateTuple[0], 10);
         month = parseInt(dateTuple[1], 10);
         year = parseInt(dateTuple[2], 10);
         hour = parseInt(timeTuple[0], 10);
         minute = parseInt(timeTuple[1], 10);
         
         var date = new Date(year, month-1, day, hour, minute);
         
         return parseInt(date.getTime(), 10);
      },
      formatDate:function(year, month, day){
         if(day < 10){
            day = '0' + day;
         }
         if(month < 10){
            month = '0' + month;
         }
         return day + '-' + month + '-' + year;
      },
      formatTime:function(hour, minute){
         if(hour < 10){
            hour = '0' + hour;
         }
         if(minute < 10){
            minute = '0' + minute;
         }
         return hour + ':' + minute;
      },
      adjustDate:function(){
         var fromTime = $('#fromtime').val();
         var fromDate = $('#from').val();
         // var fromTimestamp = Calendar.Util.dateTimeToTimestamp(fromDate, fromTime);
         var date = new Date();
         var nowTime = date.getTime();

         // if(fromTimestamp >= toTimestamp){
         //    fromTimestamp += 30*60*1000;
         //    var date = new Date(fromTimestamp);
         //    movedTime = Calendar.Util.formatTime(date.getHours(), date.getMinutes());
         //    movedDate = Calendar.Util.formatDate(date.getFullYear(),
         //          date.getMonth()+1, date.getDate());

         //    $('#to').val(movedDate);
         //    $('#totime').val(movedTime);
         // }
      }
   },
   UI:{
      // scrollcount: 0,
      loading: function(isLoading){
         if (isLoading){
            $('#loading').show();
         }else{
            $(window).resize();
            $('#loading').hide();
         }
      },
      startEventDialog:function(){
         Calendar.UI.loading(false);
         $('#fullcalendar').fullCalendar('unselect');
         var scrolltop = $(window).scrollTop();
         $("#modal_holder").css({top:scrolltop+75}).modal("show");
         Calendar.UI.Share.init();
      },
      newEvent:function(start, end, allday){
         start = Math.round(start.getTime()/1000);
         if (end){
            end = Math.round(end.getTime()/1000);
         }
         if ($("#modal_holder").css("display") == 'block') {
            $('#modal_holder').modal('hide');
         } else {
            Calendar.UI.loading(true);
            $.ajax({
               type: "GET",
               url: OC.filePath('calendar', 'ajax/event', 'new.form.php'),
               data: {start:start, end:end, allday:allday?1:0},
               dataType: 'html',
               success: function(data) {
                  if (!isLoggedIn(data, target)) {
                     window.location = login_url;
                     return false;
                  }

                  $('#modal_holder').html(data);
                  if($.isFunction($.fn.placeholder)) {
                     $("input, textarea", "#modal_holder").placeholder();
                  }

                  // Init event form validate
                  $("#modal_holder #event_form").validate({
                     errorPlacement:function(error,element) {
                        if ( element.attr("name") == "during[]" ) {
                           error.insertAfter("#addinterviewer");
                        } else {
                           error.insertAfter(element);
                        }
                     },
                     submitHandler: function(form) {
                        $("#modal_holder #event_form").ajaxSubmit({
                           type: 'post',
                           dataType: "json",
                              beforeSubmit: function(data, form, options) {
                                 if (!showLoading("#modal_holder #submitNewEvent", options, null, {button:true}))
                                    return false;
                                 $("#modal_holder #errorbox").hide();
                              },
                              success: function(data) {
                                 try {
                                    var retmsg = data;
                                    if (retmsg.error) {
                                       $("#modal_holder #errorbox").jobUtil('showError', retmsg.error);
                                    }
                                    else if(retmsg.success) {
                                       $('#modal_holder').modal('hide');
                                       $('#fullcalendar').fullCalendar('refetchEvents');
                                    }
                                 } catch(e) {
                                    return false;
                                 }
                              }
                        });
                     }
                  });
                  Calendar.UI.startEventDialog();
                  $('#preview_modal').hide();
               }
            });
         }
      },
      previewEvent:function(calEvent, jsEvent, view){
         if (calEvent.editable == false || calEvent.source.editable == false) {
            return;
         }
         var target = $(this);
         var id = calEvent.id;
         var share = $('#fullcalendar').attr('data-share');
         var userid = $('#fullcalendar').attr('data-userid');

         if( $("#preview_holder").css("display") != 'none' ){
            $('#preview_holder').hide();
         } else {
            $('#loading').show();
            $.ajax({
               type: "GET",
               url: OC.filePath('calendar', 'ajax/event', 'preview.php'),
               data: {id: id, share: share, userid: userid},
               dataType: 'html',
               cache: false, 
               success: function(data) {
                  if (!isLoggedIn(data, target)) {
                     window.location = login_url;
                     return false;
                  }
                  if ( data == 'No events found.' ) {
                     showMessagePanel(t('calendar', 'No events found.'), target, true, {placement:'top'});
                     $('#loading').hide();
                     return false;
                  }

                  $('#preview_holder').html(data);
                  $("#preview_holder .contentline_each a").tooltip();
                  Calendar.UI.showPreviewModal(target);
               }
            });
         }
      },
      showPreviewModal:function(target){
         $('#loading').hide();
         // Init remind feedback js
         $('#preview_holder #remind').click(function() {
            $.metadata.setType('attr', 'data');
            var target = $(this);
            var data = target.metadata();
            var objectid = data.objectid;
            var jobid = data.jobid;

            $.ajax({
               type: "POST",
               url: remindfeedback_url,
               data: {objectid: objectid, jobid: jobid},
               dataType: 'json',
               beforeSend: function(xhr, settings) {
                  showLoading(target, settings, null, {button:true});
               },
               success: function(data) {
                  try {
                     var retmsg = data;
                     if (retmsg.error) {
                        showMessagePanel(retmsg.error, target, true, {placement:'right'});
                     }
                     else if(retmsg.success) {
                        target.parent().html('<span>'+retmsg.success+'</span>');
                     }
                  } catch(e) {
                     return false;
                  }
               }
            })
         });
         $("#preview_holder").show().position({
            my: "left top",
            at: "right top",
            of: target
         });

      },
      /*submitDeleteEventForm:function(url){
         var post = $('#event_form').serialize();
         $('#errorbox').empty();
         Calendar.UI.loading(true);
         $.post(url, post, function(data){
               Calendar.UI.loading(false);
               if(data.status == 'success'){
                  $('#fullcalendar').fullCalendar('removeEvents', $('#event_form input[name=id]').val());
                  // $('#event').dialog('destroy').remove();
                  $('#event').modal('hide');
               } else {
                  $('#errorbox').html(t('calendar', 'Deletion failed'));
               }

         }, "json");
      },*/
      validateEventForm:function(url){
         $("#errorbox").empty();
         $.ajax({
            type: "POST",
            url: url,
            data: $("#event_form").serialize(),
            dataType: 'json',
            beforeSend: function(xhr, settings) {
               if(!showLoading($('#event_form')))
                  return false;
            },
            success: function(data) {
               try {
                  var retmsg = data;
                  if (retmsg.error) {
                     $("#errorbox").jobUtil('showError', retmsg.error);
                  }
                  else if(retmsg.success) {
                     $('#modal_holder').modal('hide');
                     $('#fullcalendar').fullCalendar('refetchEvents');
                  }
               } catch(e) {
                  return false;
               }
            }
         })
      },
      /* Remove below functions
      moveEvent:function
      resizeEvent:function
      showadvancedoptions:function
      showadvancedoptionsforrepeating:function
      */
      getEventPopupText:function(event){
         if (event.allDay){
            var timespan = $.fullCalendar.formatDates(event.start, event.end, 'ddd d MMMM[ yyyy]{ - [ddd d] MMMM yyyy}', {monthNamesShort: monthNamesShort, monthNames: monthNames, dayNames: dayNames, dayNamesShort: dayNamesShort}); //t('calendar', "ddd d MMMM[ yyyy]{ - [ddd d] MMMM yyyy}")
         }else{
            var timespan = $.fullCalendar.formatDates(event.start, event.end, 'ddd d MMMM[ yyyy] ' + defaulttime + '{ - [ ddd d MMMM yyyy]' + defaulttime + '}', {monthNamesShort: monthNamesShort, monthNames: monthNames, dayNames: dayNames, dayNamesShort: dayNamesShort}); //t('calendar', "ddd d MMMM[ yyyy] HH:mm{ - [ ddd d MMMM yyyy] HH:mm}")
            // Tue 18 October 2011 08:00 - 16:00
         }
         var html =
            '<div class="summary">' + escapeHTML(event.title) + '</div>' +
            '<div class="timespan">' + timespan + '</div>';
         if (event.description){
            html += '<div class="description">' + escapeHTML(event.description) + '</div>';
         }
         return html;
      },
      /* Remove lockTime: function*/
      /* Remove showCalDAVUrl: function*/
      /* Remove repeat: function*/
      /* Remove setViewActive: function*/
      categoriesChanged:function(newcategories){
         categories = $.map(newcategories, function(v) {return v;});
         // console.log('Calendar categories changed to: ' + categories);
         $('#category').multiple_autocomplete('option', 'source', categories);
      },
      Calendar:{
         changejob:function(target, calendarid, jobid, jobtitle, prev_source)
         {
            $.ajax({
               type: "POST",
               url: OC.filePath('calendar', 'ajax', 'changejob.php'),
               data: { calendarid: calendarid, jobid: jobid },
               dataType: 'json',
               beforeSend: function(xhr, settings) {
                  showLoading(target, settings, null, {button: true});
               },
               success: function(data){
                  try {
                     var retmsg = data;
                     if (retmsg.error) {
                        showMessagePanel(retmsg.error, $('.hr_innerwrap #joblinks'), true, {placement:'right'});
                     }
                     else if(retmsg.success) {
                        var retdata = retmsg.success;
                        $('#changejob a').removeClass('cur_a');
                        target.addClass('cur_a');
                        $('#changejob').attr('pjobid',jobid);
                        $('#joblinks .needp_relative b').html(jobtitle);
                        $("#joblinks").removeClass("open");

                        // Refetch cal data
                        $('#fullcalendar').fullCalendar('removeEventSource', prev_source);
                        $('#fullcalendar').fullCalendar('addEventSource', retdata.eventSource);
                     }
                  } catch(e) {
                     return false;
                  }
               }
            });
         },
      },
      /* Remove Calendar:{
         overview:function
         activation:function
         newCalendar:function
         edit:function
         deleteCalendar:function
         submit:function
         cancel:function
         colorPicker:function
      },*/
      Share:{
         init:function(){
            // var itemShares = [OC.Share.SHARE_TYPE_USER, OC.Share.SHARE_TYPE_GROUP];
            $('#sharewith').autocomplete({minLength: 2, source: function(search, response) {
               $.get(OC.filePath('core', 'ajax', 'share.php'), { fetch: 'getShareWith', search: search.term, itemShares: itemShares }, function(result) {
                  if (result.status == 'success' && result.data.length > 0) {
                     response(result.data);
                  }
               });
            },
            focus: function(event, focused) {
               event.preventDefault();
            },
            select: function(event, selected) {
               var itemType = 'event';
               var itemSource = $('#sharewith').data('item-source');
               var shareType = selected.item.value.shareType;
               var shareWith = selected.item.value.shareWith;
               $(this).val(shareWith);
               // Default permissions are Read and Share
               var permissions = OC.PERMISSION_READ | OC.PERMISSION_SHARE;
               OC.Share.share(itemType, itemSource, shareType, shareWith, permissions, function(data) {
                  var newitem = '<li data-item-type="event"'
                     + 'data-share-with="'+shareWith+'" '
                     + 'data-permissions="'+permissions+'" '
                     + 'data-share-type="'+shareType+'">'+shareWith+' ('+(shareType == OC.Share.SHARE_TYPE_USER ? t('core', 'user') : t('core', 'group'))+')'
                     + '<span class="shareactions"><input class="update" type="checkbox" title="'+t('core', 'Editable')+'">'
                     + '<input class="share" type="checkbox" title="'+t('core', 'Shareable')+'" checked="checked">'
                     + '<input class="delete" type="checkbox" title="'+t('core', 'Deletable')+'">'
                     + '<img class="svg action delete" title="Unshare"src="'+ OC.imagePath('core', 'actions/delete.svg') +'"></span></li>';
                  $('.sharedby.eventlist').append(newitem);
                  $('#sharedWithNobody').remove();
                  $('#sharewith').val('');
               });
               return false;
            }
            });

            $('.shareactions > input:checkbox').change(function() {
               var container = $(this).parents('li').first();
               var permissions = parseInt(container.data('permissions'));
               var itemType = container.data('item-type');
               var shareType = container.data('share-type');
               var itemSource = container.data('item');
               var shareWith = container.data('share-with');
               var permission = null;
               if($(this).hasClass('update')) {
                  permission = OC.PERMISSION_UPDATE;
               } else if($(this).hasClass('share')) {
                  permission = OC.PERMISSION_SHARE;
               } else if($(this).hasClass('delete')) {
                  permission = OC.PERMISSION_DELETE;
               }
               // This is probably not the right way, but it works :-P
               if($(this).is(':checked')) {
                  permissions += permission;
               } else {
                  permissions -= permission;
               }
               OC.Share.setPermissions(itemType, itemSource, shareType, shareWith, permissions);
            });

            $('.shareactions > .delete').click(function() {
               var container = $(this).parents('li').first();
               var itemType = container.data('item-type');
               var shareType = container.data('share-type');
               var itemSource = container.data('item');
               var shareWith = container.data('share-with');
               OC.Share.unshare(itemType, itemSource, shareType, shareWith, function() {
                  container.remove();
               });
            });
         }
      },
      Drop:{
         init:function(){
            if (typeof window.FileReader === 'undefined') {
               return false;
            }
            droparea = document.getElementById('fullcalendar');
            droparea.ondrop = function(e){
               e.preventDefault();
               Calendar.UI.Drop.drop(e);
            }
         },
         drop:function(e){
            var files = e.dataTransfer.files;
            for(var i = 0;i < files.length;i++){
               var file = files[i];
               var reader = new FileReader();
               reader.onload = function(event){
                  Calendar.UI.Drop.doImport(event.target.result);
                  $('#fullcalendar').fullCalendar('refetchEvents');
               }
               reader.readAsDataURL(file);
            }
         },
         doImport:function(data){
            $.post(OC.filePath('calendar', 'ajax/import', 'dropimport.php'), {'data':data},function(result) {
               if(result.status == 'success'){
                  $('#fullcalendar').fullCalendar('addEventSource', result.eventSource);
                  $('#notification').html(result.message);
                  $('#notification').slideDown();
                  window.setTimeout(function(){$('#notification').slideUp();}, 5000);
                  return true;
               }else{
                  $('#notification').html(result.message);
                  $('#notification').slideDown();
                  window.setTimeout(function(){$('#notification').slideUp();}, 5000);
               }
            });
         }
      }
   },

}
$.fullCalendar.views.list = ListView;
function ListView(element, calendar) {
   var t = this;

   // imports
   jQuery.fullCalendar.views.month.call(t, element, calendar);
   var opt = t.opt;
   var trigger = t.trigger;
   var eventElementHandlers = t.eventElementHandlers;
   var reportEventElement = t.reportEventElement;
   var formatDate = calendar.formatDate;
   var formatDates = calendar.formatDates;
   var addDays = $.fullCalendar.addDays;
   var cloneDate = $.fullCalendar.cloneDate;
   function skipWeekend(date, inc, excl) {
      inc = inc || 1;
      while (!date.getDay() || (excl && date.getDay()==1 || !excl && date.getDay()==6)) {
         addDays(date, inc);
      }
      return date;
   }

   // overrides
   t.name='list';
   t.render=render;
   t.renderEvents=renderEvents;
   t.setHeight=setHeight;
   t.setWidth=setWidth;
   t.clearEvents=clearEvents;

   function setHeight(height, dateChanged) {
   }

   function setWidth(width) {
   }

   function clearEvents() {
      this.reportEventClear();
   }

   // main
   function sortEvent(a, b) {
      return a.start - b.start;
   }

   function render(date, delta) {
      if (!t.start){
         t.start = addDays(cloneDate(date, true), -7);
         t.end = addDays(cloneDate(date, true), 7);
      }
      if (delta) {
         if (delta < 0){
            addDays(t.start, -7);
            addDays(t.end, -7);
            if (!opt('weekends')) {
               skipWeekend(t.start, delta < 0 ? -1 : 1);
            }
         }else{
            addDays(t.start, 7);
            addDays(t.end, 7);
            if (!opt('weekends')) {
               skipWeekend(t.end, delta < 0 ? -1 : 1);
            }
         }
      }
      t.title = formatDates(
         t.start,
         t.end,
         opt('titleFormat', 'week')
      );
      t.visStart = cloneDate(t.start);
      t.visEnd = cloneDate(t.end);
   }

   function eventsOfThisDay(events, theDate) {
      var start = cloneDate(theDate, true);
      var end = addDays(cloneDate(start), 1);
      var retArr = new Array();
      for (i in events) {
         var event_end = t.eventEnd(events[i]);
         if (events[i].start < end && event_end >= start) {
            retArr.push(events[i]);
         }
      }
      return retArr;
   }

   function renderEvent(event) {
      if (event.allDay) { //all day event
         var time = opt('allDayText');
      }
      else {
         var time = formatDates(event.start, event.end, opt('timeFormat', 'agenda'));
      }
      var classes = ['fc-event', 'fc-list-event'];
      classes = classes.concat(event.className);
      if (event.source) {
         classes = classes.concat(event.source.className || []);
      }
      var html = '<tr>' +
         '<td>&nbsp;</td>' +
         '<td class="fc-list-time">' +
         time +
         '</td>' +
         '<td>&nbsp;</td>' +
         '<td class="fc-list-event">' +
         '<span id="list' + event.id + '"' +
         ' class="' + classes.join(' ') + '"' +
         '>' +
         '<span class="fc-event-title">' +
         escapeHTML(event.title) +
         '</span>' +
         '</span>' +
         '</td>' +
         '</tr>';
      return html;
   }

   function renderDay(date, events) {
      var dayRows = $('<tr>' +
         '<td colspan="4" class="fc-list-date">' +
         '<span>' +
         formatDate(date, opt('titleFormat', 'day')) +
         '</span>' +
         '</td>' +
         '</tr>');
      for (i in events) {
         var event = events[i];
         var eventElement = $(renderEvent(event));
         triggerRes = trigger('eventRender', event, event, eventElement);
         if (triggerRes === false) {
            eventElement.remove();
         }else{
            if (triggerRes && triggerRes !== true) {
               eventElement.remove();
               eventElement = $(triggerRes);
            }
            $.merge(dayRows, eventElement);
            eventElementHandlers(event, eventElement);
            reportEventElement(event, eventElement);
         }
      }
      return dayRows;
   }

   function renderEvents(events, modifiedEventId) {
      events = events.sort(sortEvent);

      var table = $('<table class="fc-list-table"></table>');
      var total = events.length;
      if (total > 0) {
         var date = cloneDate(t.visStart);
         while (date <= t.visEnd) {
            var dayEvents = eventsOfThisDay(events, date);
            if (dayEvents.length > 0) {
               table.append(renderDay(date, dayEvents));
            }
            date=addDays(date, 1);
         }
      }

      this.element.html(table);
   }
}
$(document).ready(function(){
   $('#fullcalendar').fullCalendar({
      header: false,
      firstDay: firstDay,
      editable: false, // disable default drag and resize
      defaultView: defaultView,
      timeFormat: {
         agenda: agendatime,
         '': defaulttime
      },
      columnFormat: {
         month: t('calendar', 'ddd'),    // Mon
         week: t('calendar', 'ddd M/d'), // Mon 9/7
         day: t('calendar', 'dddd M/d')  // Monday 9/7
      },
      titleFormat: {
         month: t('calendar', 'yyyy年 M月'),
               // September 2009
         week: t('calendar', "MMM d[ yyyy]{ '&#8212;'[ MMM] d yyyy}"),
               // Sep 7 - 13 2009
         day: t('calendar', 'dddd, MMM d, yyyy'),
               // Tuesday, Sep 8, 2009
      },
      axisFormat: defaulttime,
      monthNames: monthNames,
      monthNamesShort: monthNamesShort,
      dayNames: dayNames,
      dayNamesShort: dayNamesShort,
      // allDayText: allDayText,
      viewDisplay: function(view) {
         $('#datecontrol_date').val($('<p>').html(view.title).text());
         if (view.name != defaultView) {
            $.post(OC.filePath('calendar', 'ajax', 'changeview.php'), {v:view.name});
            defaultView = view.name;
         }
         // Calendar.UI.setViewActive(view.name);
      },
      columnFormat: {
          week: 'ddd d. MMM'
      },
      selectable: true,
      selectHelper: true,
      // select: Calendar.UI.newEvent,
      eventClick: Calendar.UI.previewEvent,
      eventRender: function(event, element) {
         element.find('.fc-event-title').text($("<div/>").html(escapeHTML(event.title)).text());
      },
      loading: Calendar.UI.loading,
      eventSources: eventSources,
      year: $('#fullcalendar').data('startyear'),
      month: $('#fullcalendar').data('startmonth')
   });
   $("#datecontrol_date").on("click",function() {
      var $input = $(this);
      var nowDate = {}, now = new Date(), year = now.getFullYear(), month = now.getMonth(), day = now.getDate();
      nowDate.date = new Date(year, month, day);
      nowDate.year = nowDate.date.getFullYear();
      nowDate.month = nowDate.date.getMonth() + 1;
      nowDate.day = nowDate.date.getDate() + 1;
      nowDate.minYear = nowDate.year - 3;
      nowDate.maxYear = nowDate.year;
      if($('#ppp_dateselect').length <= 0){
         var yearul = '<ul class="pull-left">';
         var monthdiv = '<div class="ppp_timepicker_right pull-left">';
         for(tyear=nowDate.year; tyear>=nowDate.minYear; tyear--){
            yearul += '<li class="year" data-year="' + tyear + '">' + tyear + '</li>';
            monthdiv += '<div class="ptr_eachmonth clearfix">';
            for(tmonth=1; tmonth<=12; tmonth++){
               disable_month = (tyear==nowDate.year && tmonth>nowDate.month);
               monthdiv += '<div class="pull-left"><a href="javascript:;" ' + (disable_month ? 'class="notsldcur_a"' : 'class="month" data-month="' + tmonth + '"') + '>' + tmonth + '</a></div>';
            }
            monthdiv += '</div>';
         }
         yearul += '</ul>';
         var monthhtml = '<div class="ppp_timepicker ppp_timepicker_month clearfix">' + yearul + monthdiv + '</div>';
         var datehtml = '<div id="ppp_dateselect" class="ppp_timepickerwrap popup hide" style="position:fixed; z-index:102;">' + monthhtml + '</div>';
         $('body').append(datehtml);

         // to mark which is the min view unit
         $('#ppp_dateselect .ppp_timepicker_month .month').addClass('minview');

         $('#ppp_dateselect').on('click', '.ppp_timepicker ul li',function(){
            var indexnum = $(this).index();
            $(this).addClass('sldcur_li').siblings().removeClass('sldcur_li');
            $(this).closest('ul').next('.ppp_timepicker_right').children().eq(indexnum).show().siblings().hide();
         });
      }
      
      datevalue = $input.val().replace(/年|月/g, '-');
      datevalue = datevalue.split('-');
      var yearindex = $('#ppp_dateselect .ppp_timepicker_month .year[data-year='+datevalue[0]+']').index();
      $('#ppp_dateselect .ppp_timepicker_month .year').eq(yearindex).addClass('sldcur_li').siblings().removeClass('sldcur_li');
      $('#ppp_dateselect .ppp_timepicker_month .ptr_eachmonth .month').removeClass('sldcur_a');
      $('#ppp_dateselect .ppp_timepicker_month .ptr_eachmonth:eq('+yearindex+') .month[data-month='+datevalue[1]+']').addClass('sldcur_a').siblings().removeClass('sldcur_a');
      $('#ppp_dateselect .ppp_timepicker_month .ptr_eachmonth').eq(yearindex).show().siblings().hide();
      $('#ppp_dateselect .ppp_timepicker_month').show().siblings().hide();
      $('#ppp_dateselect').show().position({
         of: $(this),
         my: 'left top',
         at: 'left bottom'
      });
      
      $('#ppp_dateselect').off('.ppp_dateselect').on('click.ppp_dateselect', '.minview', function(){
         $(window).resize();
         $('#fullcalendar').fullCalendar('gotoDate', $("#ppp_dateselect .sldcur_li").html(),$(this).data("month")-1);
         $('#ppp_dateselect').hide();
      });
   });


   OCCategories.changed = Calendar.UI.categoriesChanged;
   OCCategories.app = 'calendar';
   OCCategories.type = 'event';
   $('#onemonthview_radio').click(function(){
      $(window).resize();
      $('#fullcalendar').fullCalendar('changeView', 'month');
   });
   $('#today_input').click(function(){
      $(window).resize();
      $('#fullcalendar').fullCalendar('today');
   });
   $('#datecontrol_left').click(function(){
      $(window).resize();
      $('#fullcalendar').fullCalendar('prev');
   });
   $('#datecontrol_right').click(function(){
      $(window).resize();
      $('#fullcalendar').fullCalendar('next');
   });
   
   Calendar.UI.Share.init();
   Calendar.UI.Drop.init();

   $('#fullcalendar').fullCalendar('option', 'height', $(window).height() - $('#controls').height() - $('#header').height() - 84);

   $(window).resize(function(){
      $('#fullcalendar').fullCalendar('option', 'height', $(window).height() - $('#controls').height() - $('#header').height() - 84);
   });

   // Change job control
   $('#changejob').delegate("a", "click", function(event) {
      var target = $(this);
      var target_class = target.attr('class');
      if ( target_class == 'last_lookmore' ) {
         return false;
      };
      var jobid = target.attr("id");
      var jobtitle = target.html();
      var calendarid = $('#fullcalendar').attr('data-calid');
      var prev_jobid = $('#changejob').attr('pjobid');
      var prev_source = OC.filePath('calendar', 'ajax', 'events.php')+"?calendar_id="+calendarid;

      if ( prev_jobid > 0 ) {
         prev_source += "&jobid="+prev_jobid;
      }
      
      // Reload calendar's source
      Calendar.UI.Calendar.changejob(target, calendarid, jobid, jobtitle, prev_source);
      return false;
   });

   $('#changejob').on('click', '.last_lookmore', function() {
      var jobid = $('#changejob').attr('pjobid');
      var list_url = joblist_url+"?cview=1";

      if(jobid > 0) {
         var list_url = getUrlQuery(list_url, "jobid="+jobid);
      }

      $("#joblinks").removeClass("open");

      $(this).jobSelect({
         title: '选择职位',
         listurl: list_url,
         calendarview: function() {
            var target = $(this);
            var jobid = target.attr("id");
            var jobtitle = target.html();
            var calendarid = $('#fullcalendar').attr('data-calid');
            var prev_jobid = $('#changejob').attr('pjobid');
            var prev_source = OC.filePath('calendar', 'ajax', 'events.php')+"?calendar_id="+calendarid;

            if ( prev_jobid > 0 ) {
               prev_source += "&jobid="+prev_jobid;
            }

            // Reload calendar's source
            Calendar.UI.Calendar.changejob(target, calendarid, jobid, jobtitle, prev_source);
            $('#floatcontainer').modal('hide');
            return false;
         }
      });
   });
});
